package edu.hit.crawler;

import java.io.IOException;
import java.net.URL;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import edu.hit.crawler.io.CrawItem;
import edu.hit.crawler.io.FetchOutput;

/**
 * Inject urls to db.
 */
@SuppressWarnings("deprecation")
public class DocReader extends Configured implements Tool {

	public static Logger logger = Logger.getLogger(DocReader.class);

	public static class ReadMapper extends
			Mapper<CrawItem, FetchOutput, Text, FetchOutput> {

		public void map(CrawItem key, FetchOutput value, Context context)
				throws IOException, InterruptedException {
			String host = new URL(value.getUrl()).getHost();
			context.write(new Text(host), value);
		}
	}

	public static class ReadReducer extends
			Reducer<Text, FetchOutput, Text, FetchOutput> {

		@Override
		public void reduce(Text key, Iterable<FetchOutput> values,
				Context context) throws IOException, InterruptedException {
			for (FetchOutput value : values) {
				context.write(key, value);
			}

		}
	}

	public static void main(String[] args) throws Exception {

		//PropertyConfigurator.configure("conf/log4j.properties");
		int res = ToolRunner.run(new Configuration(), new DocReader(), args);
		System.exit(res);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.hadoop.util.Tool#run(java.lang.String[])
	 */
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.hadoop.util.Tool#run(java.lang.String[])
	 */
	@Override
	public int run(String[] args) throws Exception {
		// configure a job and start it
		Configuration conf = getConf();
		Job job = new Job(conf, "read");
		job.setJarByClass(Crawler.class);
		job.setMapperClass(ReadMapper.class);
		job.setReducerClass(ReadReducer.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(FetchOutput.class);
		
		job.setOutputFormatClass(SequenceFileOutputFormat.class);

		job.setNumReduceTasks(2);

		String workdir = conf.get("org.work.crawler.dir", "crawler/");
		FileInputFormat.addInputPath(job, new Path(workdir + "doc/"
				+ "2012_06_25_08_52_59"));

		Path out = new Path(workdir + "final_doc/");

		SequenceFileOutputFormat.setOutputPath(job, out);

		int res = job.waitForCompletion(true) ? 0 : 1;

		if (res == 0) {
			System.out.println("read done!");
		} else {
			System.out.println("read failed.");
		}

		return res;
	}
}
